

package xib.core;

import java.util.ArrayList;
import xib.Page;
import xib.Panel;
import xib.parserTools.interfaces.IPageData;
import xib.parserTools.interfaces.IPanelData;

/**
 *
 * @author Xavier
 */
final class PageXib implements Page{

    /**
     * Attribute with the height of the page.
     */
    private int height;

    /**
     * Attribute with the width of the page.
     */
    private int width;

    /**
     * Attribute with the panels list present in this page.
     */
    private ArrayList<PanelXib> panels;

    /**
     * Constructor by default
     * @param page
     */
    public PageXib(IPageData page){

        //First step we validate the PageData
        page.validate();

        height = page.getHeight();
        width = page.getWidth();

        ArrayList<IPanelData> list = page.getPanels();
        panels = new ArrayList<PanelXib>();
        for(int i=0; i < list.size(); i++){
            panels.add(new PanelXib(list.get(i)));
        }   
    }

    /**
     * Obtain the height from the page.
     * @return integer
     */
    public int getHeight(){
        return height;
    }

    /**
     * Obtain the width from the page.
     * @return integer
     */
    public int getWidth(){
        return width;
    }


    /**
     * Obtain the panel in the position.
     * @param position must be between 1 and the quantity of panels.
     * @return PanelXib
     * @throws IllegalArgumentException if the position is out of range.
     */
    public Panel getPanel(int position){
        if(position < 1 || position > panels.size())
            throw new IllegalArgumentException("No panel exists in this " +
                "position, position must be between 1 and " + panels.size());
        return panels.get(position - 1);
    }

    /**
     * Obtain the quantity of panels presents
     * @return integer
     */
    public int getQuantityOfPanels(){
        return panels.size();
    }

    public Panel getPanelByLocation(int locationX, int locationY){
        if(locationX > width || locationY > height){
            throw new IllegalStateException("Muerete");
        }

        int size = panels.size();
        int x,y;
        Panel panel, res = null;
        for(int i=0; i < size; i++){
            panel = panels.get(i);
            x = panel.getLocationX();
            if(locationX >= x && locationX <= x + panel.getWidth()){
                y = panel.getLocationY();
                if( locationY >= y && locationY <= y + panel.getHeight()){
                    i = size + 1;
                    res = panel;
                }
            }
        }
        return res;
    }
}
